import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton,QWidget
from PyQt5.QtCore import QObject, Qt, pyqtSignal

# 自定义信号类
class MySignal(QObject):
    instance = None
    status_signal = pyqtSignal(str)

    @classmethod
    def my_signal(cls):
        if cls.instance:
            return cls.instance
        else:
            obj = cls()
            cls.instance = obj
            return cls.instance
            
    def status_emit(self, s):
        self.status_signal.emit(s)


# 自定义按钮类，继承自QPushButton
class MyPushButton(QPushButton):
    def __init__(self, *args):
        super(MyPushButton, self).__init__(*args)        
        # 打开鼠标追踪，如果不打开只有鼠标按下才会同时触发鼠标移到事件
        self.setMouseTracking(True)
    
    # 重写QPushButton中的鼠标移动事件
    def mouseMoveEvent(self, event):
        # 触发信号，并携带鼠标位置的字符串
        MySignal.my_signal().status_emit(str(event.pos().x())+str(event.pos().y()))
        self.update()
    # 重写键盘按下事件
    def keyPressEvent(self, event):
        # 如果按下xxx则xxx
        if event.key() == Qt.Key_Home:
            logging.info('Home')
        # 组合键
        elif (event.key() == Qt.Key_P):
           if QApplication.keyboardModifiers() == Qt.ShiftModifier:
               logging.info('shift + p')
           else :
               logging.info('p')
        else:
            QWidget.keyPressEvent(self, event)

class MainWindow(QMainWindow):
    """
    主窗口类
    """
    Status_signal = MySignal.my_signal().status_signal
    def show_dialog(self):
        pass
    def __init__(self, *args):
        super(MainWindow, self).__init__(*args)

        # 设置主窗口的标题及大小
        self.setWindowTitle('主窗口')
        self.resize(400, 300)

       # 使自定义的按钮类来实例化按钮
        self.btn = MyPushButton(self)
        self.btn.setText('自定义按钮')
        self.btn.move(50, 50)
        self.btn.clicked.connect(self.show_dialog)

        # 自定义信号绑定
        self.Status_signal.connect(self.show_status)
     
     # 在状态栏中显示字符串
    def show_status(self, s):
        self.statusBar().showMessage(s)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = MainWindow()
    demo.show()
    sys.exit(app.exec())
